package com.wang.vedio.fragment.search;

import android.content.Context;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxui.fragment.NewLazyFragment;
import com.wang.vedio.R;
import com.wang.vedio.adapter.index.SearchAdapter;
import com.wang.vedio.event.EventTag;
import com.wang.vedio.event.MessageEvent;
import com.wang.vedio.net.SharedHelper;
import com.wang.vedio.net.entity.BaseBean;
import com.wang.vedio.net.entity.DictionaryBean;
import com.wang.vedio.net.entity.VideoBean;
import com.wang.vedio.net.rxjava.HttpMethods;
import com.wang.vedio.net.subscribers.ProgressSubscriber;
import com.wang.vedio.net.subscribers.SubscriberOnNextListener;
import com.wang.vedio.player.PlayerActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 描述：线索发现
 */
public class SearchLabelFragment extends NewLazyFragment{
    @BindView(R.id.rec_main)
    RecyclerView recMain;
    @BindView(R.id.srl_all)
    SmartRefreshLayout srlAll;
    Unbinder unbinder;

    private String typeName;

    public static SearchLabelFragment getInstance(String typeName) {
        SearchLabelFragment fragment = new SearchLabelFragment();
        fragment.typeName = typeName;
        return fragment;
    }

    public void nextPage(){
        page++;
        getData();
    }

    @Override
    protected int getContentViewId() {
        return R.layout.gyss_fragment_search_child_layout;
    }

    @Override
    protected void initView(View view) {
        unbinder = ButterKnife.bind(this, view);
        init();
        initSrl();
        super.initView(view);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshData(MessageEvent messageEvent) {
        if (messageEvent.getTag().equals(EventTag.DT)) {
            refresh();
        }
    }

    public void refresh() {
        srlAll.setEnableLoadMore(false);
        isShowDialog = false;
        page = 1;
        srlAll.setEnableLoadMore(false);
        mList.clear();
        getData();
    }

    private Context context;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Override
    protected void initData() {
        typeName = getArguments().getString("typeName");
    }

    @Override
    public void onResume() {
        super.onResume();
        refresh();
    }

    private String startTime = "";
    private String endTime = "";

    private void getData() {
        SubscriberOnNextListener<BaseBean<List<VideoBean>>> onNextListener = baseBean -> {
            if (srlAll != null) {
                srlAll.finishLoadMore(true);
                srlAll.finishRefresh(true);
            }
            mList.clear();
            mList.addAll(baseBean.getData());
            mAdapter.notifyDataSetChanged();
        };

        Map<String,Object> params = new HashMap<>();
        params.put("pageIndex",page+"");
        params.put("typeName",typeName);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), new Gson().toJson(params));
        HttpMethods.getInstance().getVedioListByType(new ProgressSubscriber<>(onNextListener, mContext, true), requestBody);
    }

    private void initSrl() {
        srlAll.setEnableRefresh(false);
        srlAll.setEnableLoadMore(false);
        srlAll.setEnableAutoLoadMore(false);
        srlAll.setOnRefreshListener(refresh_layout -> {
            refresh();
        });
        srlAll.setOnLoadMoreListener(refresh_layout -> {
            isShowDialog = false;
            page++;
            getData();
        });
    }

    private List<VideoBean> mList;

    private List<DictionaryBean> typeList = new ArrayList<>();
    private SearchAdapter mAdapter;

    private void init() {
        mList = new ArrayList<>();
        ((SimpleItemAnimator) recMain.getItemAnimator()).setSupportsChangeAnimations(false);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 2);
        recMain.setLayoutManager(gridLayoutManager);
        mAdapter = new SearchAdapter(R.layout.item_sousuo_video,mList);
        recMain.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                getVedioById(mList.get(position).getId());
            }
        });
    }

    private void getVedioById(String vedioId){
        showLoadingDialog();
        SubscriberOnNextListener<BaseBean<VideoBean>> onNextListener = baseBean -> {
            hideLoadDialog();
            Bundle bundle = new Bundle();
            bundle.putSerializable("obj",baseBean.getData());
            RxActivityTool.skipActivity(mContext,PlayerActivity.class,bundle);
        };
        Map<String,Object> params = new HashMap<>();
        params.put("id",vedioId);
        params.put("memberId", SharedHelper.readId(mContext));
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), new Gson().toJson(params));
        HttpMethods.getInstance().getVedioById(new ProgressSubscriber<>(onNextListener, mContext, false), requestBody);
    }

    private int page = 1;
    private boolean isShowDialog = true;



    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        unbinder.unbind();
    }
}